<template>
    <div>
    <!-- 面包屑导航 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>角色管理</el-breadcrumb-item>
            <el-breadcrumb-item>角色列表</el-breadcrumb-item>
        </el-breadcrumb>   

    <!-- 卡片视图 -->
        <el-card>
    <!-- 按钮 -->
            <el-row>
                <el-col>
                     <el-button type="primary" class="roles_btn" @click="rolesAccretion=true">添加角色</el-button>
                </el-col>
            </el-row>

    <!-- 列表 -->
        <el-table :data="roleslist" stripe border >
        <!-- 展开列表 -->
            <el-table-column type="expand">
                <template slot-scope="scope">
                    <el-row v-for="(item1, i1) in scope.row.children" :key="item1.id" :class="['bdBottom',i1===0? 'bdTop':'','vcenter']" >
                        <!-- 渲染一级权限 -->
                        <el-col :span='5'>
                            <el-tag closable @close='removeDelete(scope.row,item1.id)'>{{item1.authName}}</el-tag>
                            <i class="el-icon-caret-right"></i>
                         </el-col>
                        <!-- 渲染二级和三级权限 -->
                        <el-col :span="19">
                            <el-row v-for="(item2, i2) in item1.children" :key="item2.id" :class="[i2 ===0? '' : 'bdTop','vcenter']">
                                <el-col :span="6">
                                    <el-tag type="success" closable @close='removeDelete(scope.row,item2.id)'>{{item2.authName}}</el-tag>
                                    <i class="el-icon-caret-right"></i>
                                </el-col>
                                <!-- 三级权限 -->
                                <el-col :span="13">
                                    <el-tag v-for="(item3,i3) in item2.children" :key="item3.id" type="danger" closable 
                                    @close='removeDelete(scope.row,item3.id)'>
                                        {{item3.authName}}
                                    </el-tag>                                  
                                </el-col>
                            </el-row>    
                        </el-col>                        
                    </el-row>
                </template>
            </el-table-column>

             <el-table-column type="index"></el-table-column>
             <el-table-column label='角色名称' prop="roleName"></el-table-column>
             <el-table-column label='角色描述' prop="roleDesc"></el-table-column>
             <el-table-column label='操作' width='290px'>
                 <template slot-scope="scope" >
                     <el-button type="primary" icon="el-icon-edit" size="mini" @click="rolesEdit(scope.row.id)">编辑</el-button>
                     <el-button type="danger" icon="el-icon-delete" size="mini" @click="rolesCelete(scope.row.id)">删除</el-button>
                     <el-button type="warning" icon="el-icon-share" size="mini" @click="jurisdictionBtn(scope.row)">分配权限</el-button>
                 </template>
             </el-table-column>
        </el-table>

        <!-- 添加用户弹框 -->
        <el-dialog title="添加用户"  :visible.sync="rolesAccretion" width="50%" @close='rolesClose'>
          <el-form ref="formRef" :model="rolesForm" label-width="80px" :rules="rolesRules">
            <el-form-item label="角色名称"  prop='roleName'>
            <el-input v-model="rolesForm.roleName"></el-input>
            </el-form-item>
            <el-form-item label="角色描述"  prop='roleDesc'>
            <el-input v-model="rolesForm.roleDesc"></el-input>
            </el-form-item>
          </el-form>

            <span slot="footer" class="dialog-footer">
            <el-button @click="rolesAccretion = false">取 消</el-button>
            <el-button type="primary" @click="rolesConfirm">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 编辑用户弹框 -->
        <el-dialog  title="提示" :visible.sync="rolesCompile" width="50%" @close='redactClose'>
             <el-form :model="redactForm" :rules="redactRules" ref="redactRef" label-width="80px">
                <el-form-item label="角色名称" prop="roleName">
                <el-input v-model="redactForm.roleName"></el-input>
                </el-form-item>
                <el-form-item label="角色描述" prop="roleDesc">
                <el-input v-model="redactForm.roleDesc"></el-input>
                </el-form-item>
             </el-form>

            <span slot="footer" class="dialog-footer">
            <el-button @click="rolesCompile = false">取 消</el-button>
            <el-button type="primary" @click="rolesEnsure">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 权限列表弹框 -->
        <el-dialog  title="提示" :visible.sync="jurisdiction" width="50%" @close='setRightsDiaClose'>
              <el-tree :data="jurisdictionForm" :props="treeProps" show-checkbox default-expand-all node-key='id' 
              :default-checked-keys='defkeys' ref="rolesRef"></el-tree>
              <span slot="footer" class="dialog-footer">
              <el-button @click="jurisdiction = false">取 消</el-button>
              <el-button type="primary" @click="controlPrinters">确 定</el-button>
              </span>
        </el-dialog>

  
   



      </el-card>
    </div>
</template>

<script>
export default {
   data() {
       return{
            roleslist:[],
            rolesAccretion:false,
            rolesForm:{
                roleName:'',
                roleDesc:''
            },

            // 验证
            rolesRules:{
            roleName:[
                { required: true, message: '请输入角色名称', trigger: 'blur' },
                { min: 2, max: 6, message: '长度在 2 到 6 个字符', trigger: 'blur' }
            ],
            roleDesc:[
                 { required: true, message: '请输入角色描述', trigger: 'blur' },
                { min: 2, max: 6, message: '长度在 2 到 6 个字符', trigger: 'blur' }
            ]
            },
            // 编辑
            rolesCompile : false,
            redactForm:{
                roleName:'',
                roleDesc:'',
                roleId:''
            },
            redactRules:{
                roleName:[
                { required: true, message: '请输入角色名称', trigger: 'blur' },
                { min: 2, max: 6, message: '长度在 2 到 6 个字符', trigger: 'blur' }
            ],
            roleDesc:[
                 { required: true, message: '请输入角色描述', trigger: 'blur' },
                { min: 2, max: 6, message: '长度在 2 到 6 个字符', trigger: 'blur' }
            ]
            },
            // 权限
            jurisdiction:false,

            // 所有权限列表数据
            jurisdictionForm:[],
            treeProps:{
                label:'authName',
                children: 'children'
            },
            // 默认选中的节点id值数组
            defkeys:[],
            roueId:''

            

       }
   },
   created(){
       this.getroleslist()
   },
   methods:{
      async getroleslist(){
          const {data:res} = await this.$http.get('roles')
          if(res.meta.status !==200) return this.$message.error('获取列表失败！')
          this.roleslist = res.data      
       },
      rolesClose(){
          console.log(this.$refs.formRef);
          
          this.$refs.formRef.resetFields()
      },
      rolesConfirm(){
          this.$refs.formRef.validate( async valid =>{
              if(!valid) return  
              const {data:res} = await this.$http.post('roles',this.rolesForm)
             if (res.meta.status !==201) {          
             this.rolesAccretion=false
             return this.$message.error('添加角色失败！')
         }      
            this.$message.success('添加角色成功')
            this.rolesAccretion=false
            this.getroleslist()

          })    
      },
    //   删除角色
      async rolesCelete(id){     
        const celeteData = await this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch( error => error )
        if(celeteData !== 'confirm') {
            return this.$message.info('已取消删除!')
        }
        const {data:res}  = await this.$http.delete('roles/'+id)
        console.log(res);
        
             if(res.meta.status !==200) {
            return this.$message.error('删除角色失败')
        }
        this.$message.success('删除角色成功')
        this.getroleslist()

      },
    //   查询角色
      async rolesEdit(id){       

          this.rolesCompile = true
          const {data:res} = await this.$http.get('roles/'+id)
            this.redactForm = res.data       
            
      },
    //   弹框
      redactClose(){
          this.$refs.redactRef.resetFields()
      },
    //   修改该角色
      async rolesEnsure(id){        
       
          this.$refs.redactRef.validate( async valid => {
              if (!valid) return
              const {data:res} = await this.$http.put('roles/'+this.redactForm.roleId,{
                  roleName:this.redactForm.roleName,
                  roleDesc:this.redactForm.roleDesc
              })
            //   console.log(res);
              
              if (res.meta.status !==200) {
                  return this.$message.error('修改角色失败！')
              }
              this.$message.success('修改角色成功！')
              this.rolesCompile = false
              this.getroleslist()
          })
      },
    //   删除tag事件
      async removeDelete(role,rightId){    
        const deleteTag = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(error => error)

        if (deleteTag !== 'confirm') {
            return this.$message.info('已取消删除权限列表！')
        }
        const {data:res}  = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
            if(res.meta.status !==200) {
                return this.$message.error('删除权限列表失败！')
            }
            this.$message.success('删除权限列表成功！')
    
            role.children = res.data
      },
    //   点击权限按钮
     async jurisdictionBtn(role){  
         this.roueId = role.id
         const {data:res} = await this.$http.get('rights/tree')
         if(res.meta.status !==200) {
             return this.$message.error('获取权限列表失败')
         }
        // 把获取的权限保存在Data中
        this.jurisdictionForm = res.data 
        //  调用递归 
        this.geiLeafKeys(role,this.defkeys)

       this.jurisdiction = true  
    },

    //   通过递归的形式 获取角色下面所有的三级权限id，并保存到defkeys数组中
    geiLeafKeys(node,arr) {
        //  如果当前node节点中没有children属性 则为三级权限
        if(!node.children) {
            return arr.push(node.id)
        }
        node.children.forEach(item => this.geiLeafKeys(item,arr))
    },
    //  重设递归数组
    setRightsDiaClose(){
        this.defkeys=[]
   
    },

    //  点击确定事件
    async controlPrinters(){
        const keys =[
           ... this.$refs.rolesRef.getCheckedKeys(),
            ...this.$refs.rolesRef.getHalfCheckedKeys()
        ]
        const idStr = keys.join(',')

       const {data:res} = await this.$http.post(`roles/${this.roueId}/rights`,{rids:idStr})
        if(res.meta.status !==200) {
            return this.$message.error('添加权限失败！')
        }
        this.$message.success('添加权限成功！')
        this.getroleslist()
        this.jurisdiction = false

        
        
    }










   }
}
</script>

<style lang="less" scoped>
.roles_btn {
    margin-bottom: 15px;
}
.el-tag {
    margin: 8px 5px 8px 0;
}
.bdTop {
    border-top: 1px solid #eee;
}
.bdBottom {
    border-bottom: 1px solid #eee;
}
.vcenter {
    display: flex;
    align-items: center;
}
</style>